/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="app-container" ref="pattern-container">
    <el-table :data="newPatternList" :max-height="tableHeight" id="footerBtn">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <div class="components-container board">
            <Kanban v-for="n in scope.row.ringCount" :key="n" class="kanban todo" :list="scope.row.rings[n-1]" :header-text="'环 '+n" :index="scope.$index" @fatherMethod="fatherMethod"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="No" width="45" minWidth="40">
        <template slot-scope="scope">
          <span>{{scope.$index+1}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('openatc.greenwaveoptimize.deviceid')" width="100" minWidth="40">
        <template slot-scope="scope">
          <span>{{scope.row.agentid}}</span>
        </template>
      </el-table-column>
      <el-table-column property="isValid" :label="$t('openatc.token.isValid')" align="center" width="80" prop="isused">
        <template slot-scope="scope">
          <el-switch
            style="padding-left: 5px;"
            v-model="scope.row.isused"
            active-color="#409EFF">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('openatc.greenwaveoptimize.pattern')"
        width="120"
        align="center">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.patternid"
            size="small"
            :loading="loading"
            @focus="getCurPattern(scope.row.agentid)"
            @change="changeCurPattern(scope.row,$event)">
              <el-option v-for="option in (scope.row.allPatterns)"
                         :key="option.patternid"
                         :label="option.patterndesc"
                         :value="option.patternid">
                <span>{{ option.patterndesc }}</span>
              </el-option>
          </el-select>
          <span></span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('openatc.greenwaveoptimize.directionOption1')" width="150" prop="forwardphaseDesc" :formatter="formatterForwardphaseDesc">
      </el-table-column>
      <el-table-column align="center" :label="$t('openatc.greenwaveoptimize.directionOption2')" width="150" prop="backphaseDesc" :formatter="formatterBackphaseDesc">
      </el-table-column>
      <el-table-column  align="center" :label="$t('openatc.greenwaveoptimize.offset')" width="120" prop="offset">
        <template slot-scope="scope">
          <!-- <el-input size="small" v-model.number="scope.row.offset"></el-input> -->
          <el-input-number :controls="false" :min="0" :step="1" v-model.number="scope.row.offset" size="small" style="width:70%;"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('openatc.greenwaveoptimize.cycle')" width="80" prop="cycle">
      </el-table-column>
      <el-table-column align="center" :label="$t('edge.pattern.plan')">
        <template slot-scope="scope">
          <div class="pattern-figure">
            <pattern-list
              :patternStatusList="scope.row.rings"
              :cycles="scope.row.cycle"
              :phaseList="scope.row.currPhase"
            >
            </pattern-list>
            </div>
         </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import Kanban from '../../../components/Kanban'
import { getPatternList } from '../../../api/route'
import { getMessageByCode } from '../../../utils/responseMessage'
import { getDirName } from '../../../components/SelectCrossPhase/utils.js'
export default {
  name: 'patterntable',
  components: {
    Kanban
  },
  props: {
    optList: {
      type: Array
    }
  },
  data () {
    return {
      loading: true,
      tableHeight: 460,
      screenHeight: window.innerHeight, // 屏幕高度
      newPatternList: []
    }
  },
  created () {
  },
  watch: {
    screenHeight: function () {
      // 监听屏幕高度变化
      this.tableHeight =
                window.innerHeight * 0.8 -
                document.querySelector('#footerBtn').offsetTop -
                50
    },
    optList: {
      handler: function (val) {
        if (val && val.length > 0) {
          // for () {

          // }
        }
      },
      deep: true
    },
    newPatternList: {
      handler: function (val) {
        this.$emit('onNewPatternListChange', val)
      },
      deep: true
    }
  },
  mounted: function () {
    var _this = this
    _this.$nextTick(function () {
      _this.$nextTick(function () {
        _this.tableHeight = _this.$refs['pattern-container'].offsetHeight - 20
        window.onresize = function () {
          _this.tableHeight = _this.$refs['pattern-container'].offsetHeight - 20
        }
      })
    })
  },
  methods: {
    onPatternTable (routeData, patternList, phaseList) {
      if (patternList.length === 0) {
        // this.$message.error('方案为空！')
        return
      }
      if (phaseList.length === 0) {
        // this.$message.error('相位为空！')
        return
      }
      // this.routeData = routeData
      // this.patternList = patternList
      // this.phaseList = phaseList
      this.handlePatternList(routeData, patternList, phaseList)
    },
    handlePatternList (routeData, patternList, phaseList) {
      this.newPatternList = []
      let devs = routeData.devs
      for (let pattern of patternList) {
        let obj = {}
        let id = pattern.agentid
        obj.agentid = id
        let count = [] // 计算相位有几个环
        if (pattern.feature !== undefined && pattern.feature.patternList.length !== 0) {
          let currPatternList = pattern.feature.patternList
          let dev = devs.filter(ist => ist.agentid === id)[0]
          let patternId = dev.patternid
          let currPattern
          if (Array.isArray(currPatternList)) {
            currPattern = currPatternList.filter(cpl => cpl.id === patternId)[0]
          } else {
            currPattern = currPatternList
          }
          // let currPattern = currPatternList.filter(cpl => cpl.id === patternId)[0]
          if (currPattern.desc === '') {
            obj.desc = this.$t('openatc.greenwaveoptimize.pattern') + currPattern.id
          } else {
            obj.desc = currPattern.desc
          }
          obj = {...obj, ...dev}
          obj.id = currPattern.id
          obj.offset = currPattern.offset
          obj.cycle = currPattern.cycle
          obj.patternId = currPattern.id
          obj.patternid = currPattern.id
          obj.patternDesc = currPattern.desc === '' ? `${this.$t('openatc.greenwaveoptimize.pattern')}${currPattern.id}` : currPattern.desc
          obj.allPatterns = currPatternList.map(ele => {
            let patterndesc = ele.desc === '' ? `${this.$t('openatc.greenwaveoptimize.pattern')}${currPattern.id}` : ele.desc
            return {
              patternid: ele.id,
              patterndes: ele.desc,
              patterndesc: patterndesc,
              ...ele
            }
          })
          let rings = currPattern.rings
          let currPhase = phaseList.filter(phl => phl.agentid === id)[0].feature.phaseList
          obj.currPhase = currPhase
          obj.phaseList = currPhase
          // 计算有几个环
          for (let ring of rings) {
            if (ring.length === 0) continue
            for (let rr of ring) {
              rr.desc = []
              let direction = currPhase.filter(curp => curp.id === rr.id)[0].direction // 相位方向集合
              let phaseRing = currPhase.filter(curp => curp.id === rr.id)[0].ring
              count.push(phaseRing)
              for (let dir of direction) {
                let obj = {}
                obj.id = dir
                rr.desc.push(obj)
              }
            }
          }
          obj.rings = rings
        }
        let ringCount = Array.from(new Set(count)) // 去除数组重复的元素
        ringCount = ringCount.sort(this.sortNumbers) // 把数组中的值按照从小到大的顺序重新排序
        obj.ringCount = ringCount
        this.newPatternList.push(obj)
      }
    },
    sortNumbers (a, b) {
      return a - b
    },
    fatherMethod (val) {
      let index = val.index
      let cycle = val.cycle
      this.newPatternList[index].cycle = cycle
    },
    changeCurPattern (row, curPatternid) {
      // 修改当前方案（allPatterns： 所有可选项）
      const data = {
        agentid: row.agentid,
        patternid: curPatternid,
        patterndes: row.allPatterns.filter(ele => ele.patternid === curPatternid)[0].patterndes,
        allPatterns: row.allPatterns
      }
      row.desc = data.patternDesc
      row.patternId = data.patternid
      row.patternid = data.patternid
      row.patterndes = data.patterndes
      row.allPatterns = data.allPatterns
      row.patternid = data.patternid
      let selectPattern = row.allPatterns.filter(item => item.patternid === row.patternid)[0]
      let res = this.getRings(selectPattern.rings, row.phaseList)
      row.rings = res.rings
      row.ringCount = res.ringCount
      // row.rings = selectPattern.rings
      row.cycle = selectPattern.cycle
      row.offset = selectPattern.offset
      row.currPhase = row.phaseList
    },
    getRings (ringsList, phaseList) {
      let res = {}
      let rings = JSON.parse(JSON.stringify(ringsList))
      let count = []
      // 计算有几个环
      for (let ring of rings) {
        if (ring.length === 0) continue
        for (let rr of ring) {
          rr.desc = []
          let direction = phaseList.filter(curp => curp.id === rr.id)[0].direction // 相位方向集合
          let phaseRing = phaseList.filter(curp => curp.id === rr.id)[0].ring
          count.push(phaseRing)
          for (let dir of direction) {
            let obj = {}
            obj.id = dir
            rr.desc.push(obj)
          }
        }
      }
      let ringCount = Array.from(new Set(count)) // 去除数组重复的元素
      ringCount = ringCount.sort(this.sortNumbers) // 把数组中的值按照从小到大的顺序重新排序
      res = {
        rings: rings,
        ringCount: ringCount
      }
      return res
    },
    getDirectionDesc (row, bizType) {
      let res = ''
      let desc = ''
      let phseId = -1
      let directions = []
      if (bizType === 'up') {
        desc = row.forwardphaseDesc
        phseId = row.forwardphaseid
        directions = row.forwardphasedirection
      } else {
        desc = row.backphaseDesc
        phseId = row.backphaseid
        directions = row.backphasedirection
      }
      if (!phseId) {
        return res
      }
      if (!directions) {
        directions = []
      }
      let list = directions.map(id => {
        return {
          id: id
        }
      })
      let dirNames = getDirName(list)
      if (!dirNames) {
        dirNames = []
      }
      let _this = this
      let names = dirNames.map(item => {
        let name = _this.$t(item)
        return name
      })
      desc = names.join(',')
      res = this.$t('openatc.greenwaveoptimize.phase') + phseId + ' ' + desc
      return res
    },
    formatterForwardphaseDesc (row, column) {
      let bizType = 'up'
      let res = this.getDirectionDesc(row, bizType)
      return res
    },
    formatterBackphaseDesc (row, column) {
      let bizType = 'down'
      let res = this.getDirectionDesc(row, bizType)
      return res
    },
    getCurPattern (agentid) {
      // 获取当前设备所有可选方案
      this.loading = true
      let _this = this
      // let patterns = this.newPatternList.filter(item => item.agentid === agentid)[0]
      // if (patterns.allPatterns && patterns.allPatterns.length > 0) {
      //   patterns.allPatterns = patterns.allPatterns
      //   return false
      // }
      getPatternList(agentid).then(res => {
        this.loading = false
        if (!res.data.success) {
          if (res.data.code === '4003') {
            this.$message.error(this.$t('openatc.common.devicenotonline'))
            return
          }
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        _this.newPatternList.forEach(ele => {
          if (ele.agentid === agentid) {
            ele.allPatterns = res.data.data.data.patternList.map(ele => {
              return {
                ...ele,
                patternid: ele.id,
                patterndes: ele.desc,
                patterndesc: ele.desc === '' ? `${_this.$t('openatc.greenwaveoptimize.pattern')}${ele.id}` : ele.desc
              }
            })
          }
        })
      })
    }
  }
}
</script>

<style lang="scss">
  .board {
    width: 100%;
    margin-left: 10px;
    display: flex;
    justify-content: space-around;
    flex-direction: row;
    align-items: flex-start;
  }
  // .kanban {
  //   &.todo {
  //     .board-column-header {
  //       background: $--color-primary;
  //     }
  //   }
  // }
</style>
